using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using System.Diagnostics;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Navigation;
using System.Configuration;
namespace Microsoft.IW
{
    public class MySiteCreate : SPFeatureReceiver
    {
        private SPWeb currentWeb = null;

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                SPSite mysite = properties.Feature.Parent as SPSite;
                currentWeb = mysite.OpenWeb();
                StringBuilder str = new StringBuilder();


                #region feature attempt
                //SPFeatureCollection features = currentWeb.Site.Features;
                //SPFeature publishingFeature;

                //foreach (SPFeature featureDefinition in features)
                //{
                //    str.Append(featureDefinition.Definition.DisplayName + " = " + featureDefinition.Definition.Id + " , Scope=" + featureDefinition.Definition.Scope.ToString() + "------");

                //    if (featureDefinition.Definition.DisplayName == "PublishingPrerequisites")
                //    {
                //        publishingFeature = currentWeb.Site.Features[featureDefinition.DefinitionId];
                //        break;
                //    }


                //    //foreach (SPFeature feature in currentWeb.Site.Features)
                //    //{
                //    //    str.Append("FeatureDefinition: " + feature.Definition + " = " + feature.DefinitionId + " Properties:( ");
                //    //    foreach (SPFeatureProperty prop in feature.Properties)
                //    //    {
                //    //        str.Append(prop.Name + "-" + prop.Value);
                //    //    }

                //    //    str.Append(")----------------------------------");
                //    //}

                //    //Check that each feature is scoped at the web level and     
                //    ////that it is not hidden before adding it to the list    
                //    //if ((featureDefinition.Scope == SPFeatureScope.Web) && !(featureDefinition.Hidden))    
                //    //{        
                //    //    ListItem siteFeatureItem = new ListItem("<b>" + featureDefinition.GetTitle(cInfo) + "</b><br> "                                 
                //    //        + featureDefinition.GetDescription(cInfo), featureDefinition.Id.ToString());        
                //    //    rdSiteFeatures.Items.Add(siteFeatureItem);    
                //    //}
                //   
                //}

                // System.Globalization.CultureInfo oCultureInfo = new System.Globalization.CultureInfo(1033);
                // SPFeatureDefinitionCollection collFeatureDefinitions = SPFarm.Local.FeatureDefinitions;
                // Guid guidFeatureID = new Guid("3C4CD219-D8A7-4fef-BED4-ABA672F7A21A");
                // SPFeatureDefinition oFeatureDefinition = collFeatureDefinitions.Add("Feature_Folder\\feature.xml", guidFeatureID);
                ////INSTALLED
                // SPFeatureCollection collFeatures = SPContext.Current.Site.AllWebs["Site"].Features;
                //SPFeature oFeature = currentWeb.Site.Features.Add(new Guid("A392DA98-270B-4e85-9769-04C0FDE267AA"));        

                #endregion

                EventLog eventlog = new EventLog();
                eventlog.Source = "MySiteFeatureStaple";

                try
                {
                    eventlog.WriteEntry("Starting Activation of the MySite Master Page Switcher Feature");

                    //currentWeb = (SPWeb)properties.Feature.Parent;

                    if (currentWeb.WebTemplate == "SPSPERS")
                    {

                        //look at the properties collection to get the new master page name
                        string customMaster = properties.Feature.Properties["CustomMasterName"].Value;
                        string myPeepsMaster = properties.Feature.Properties["MyPeepsMasterName"].Value;

                        //Add Blog web
                        if (!currentWeb.Webs["Blog"].Exists)
                        {
                            SPWeb blogWeb = currentWeb.Webs.Add("Blog", "Blog", String.Empty, 1033, currentWeb.Site.GetWebTemplates(1033)["BLOG#0"], false, false);
                            SPListItem item = blogWeb.Lists["Categories"].Items[0];
                            item["Title"] = "Work";
                            item.Update();
                            item = blogWeb.Lists["Categories"].Items[1];
                            item["Title"] = "Personal";
                            item.Update();
                            item = blogWeb.Lists["Categories"].Items[2];
                            item["Title"] = "Other";
                            item.Update();


                            //Add the blog to the quick launch menu
                            SPWeb quickLaunchWeb = currentWeb.Site.OpenWeb();
                            SPNavigationNodeCollection quickLaunchNodes = quickLaunchWeb.Navigation.QuickLaunch;
                            int siteNodeIndex = GetSiteNodeIndex(quickLaunchWeb);
                            string navUrl = currentWeb.Webs["Blog"].Url.Replace(currentWeb.Url + "/", "");
                            SPNavigationNode newNode = new SPNavigationNode("Blog", navUrl, false);
                            quickLaunchNodes[siteNodeIndex].Children.AddAsLast(newNode);
                            quickLaunchWeb.Update();

                            //Guid BlogMasterPageFeatureID = new Guid("e7b9e1a6-5ee7-43aa-8188-9e7acc98363d");
                            //if (currentWeb.Webs["Blog"].Features[BlogMasterPageFeatureID] == null)
                            //{
                            //    currentWeb.Webs["Blog"].Features.Add(BlogMasterPageFeatureID, true);
                            //}
                        }

                        //Create the custoim lists
                        CreateFolloweRequestList();
                        CreateTweetsList();

                        currentWeb.Description = "MySite :: " + DateTime.Now.ToShortDateString();
                        if (currentWeb.MasterUrl.Contains("default.master"))
                        {
                            currentWeb.MasterUrl = currentWeb.MasterUrl.Replace("default.master", customMaster);
                            currentWeb.CustomMasterUrl = currentWeb.MasterUrl.Replace("default.master", customMaster);
                            currentWeb.ApplyTheme("none");
                        }
                        currentWeb.Update();
                        eventlog.WriteEntry("Found site using 'SPSPERS' template & updated it with the custom master page");

                    }
                }
                catch (Exception e)
                {
                    eventlog.WriteEntry(String.Format("Error activating MySite master page switcher feature {0} : ", e.Message), EventLogEntryType.Error);
                    //if (currentWeb != null && currentWeb.WebTemplate == "SPSPERS")
                    //{
                    //    currentWeb.Site.Delete();
                    //}
                }
            });

            #region old code
            //try
            //{
            //    currentWeb = (SPWeb)properties.Feature.Parent;
            //    //look at the properties collection to get the new master page name
            //    string defaultMaster = properties.Feature.Properties["DefaultMasterName"].Value;
            //    string myPeepsMaster = properties.Feature.Properties["MyPeepsMasterName"].Value;

            //    //Add Blog web
            //    if (currentWeb.Webs["blog"] == null)
            //        currentWeb.Webs.Add("blog", "Blog", String.Empty, 1033, currentWeb.Site.GetWebTemplates(1033)["BLOG#0"], false, false);


            //    ////No need since we are replacing the defualt.master
            //    //if ((defaultMaster != null) && (defaultMaster != string.Empty))
            //    //{
            //    //    using (SPWeb curWeb = (SPWeb)properties.Feature.Parent)
            //    //    {
            //    //        //got the current site and root web in site, now set the master Url
            //    //        //to our master page that should have been uploaded as part 
            //    //        //of our feature


            //    //        if (curWeb.MasterUrl.Contains("default.master"))
            //    //        {
            //    //            curWeb.MasterUrl = curWeb.MasterUrl.Replace("default.master", defaultMaster);
            //    //            curWeb.Update();
            //    //            UpdateLog("MasterUrl property updated for web " + curWeb.Title,
            //    //                EventLogEntryType.Information);
            //    //        }
            //    //    }
            //    //}
            //}
            //catch (Exception ex)
            //{
            //    //try writing to event log
            //    UpdateLog("Error in handler: " + ex.Message, EventLogEntryType.Error);
            //}

            #endregion
        }

        public void CreateFolloweRequestList()
        {

            //web.AllowUnsafeUpdates = true;
            Guid newListGuid = currentWeb.Lists.Add("Follower requests", "Follower requests", SPListTemplateType.GenericList);

            SPList list = currentWeb.Lists[newListGuid];
            list.OnQuickLaunch = true;
            SPField field;


            list.Fields.Add("Follower", SPFieldType.User, false);
            SPFieldUser fieldUser = (SPFieldUser)list.Fields["Follower"];
            fieldUser.Description = "Follower request";
            fieldUser.Required = false;
            fieldUser.SelectionMode = SPFieldUserSelectionMode.PeopleOnly;
            fieldUser.AllowMultipleValues = false;
            fieldUser.LookupField = "Account";
            //fieldUser.LookupField = "Name";


            fieldUser.Presence = true;

            field = list.Fields.CreateNewField(SPFieldType.Boolean.ToString(), "IsAllowed");
            field.Required = false;
            field.DefaultValue = "false";
            field.Description = "Is allowed to follow me";
            list.Fields.Add(field);

            //Copy settings from the All Items view and then delete the view
            string query = list.Views["All Items"].Query;
            SPViewCollection viewcoll = list.Views;
            Guid viewID = list.Views["All Items"].ID;
            viewcoll.Delete(viewID);

            System.Collections.Specialized.StringCollection viewFields = new System.Collections.Specialized.StringCollection();

            viewFields.Add("Edit");
            viewFields.Add("Follower");
            viewFields.Add("IsAllowed");

            // Add the view to the list
            list.Views.Add("All Items", viewFields, query, 100, true, true);

            // Save the changes
            list.OnQuickLaunch = true;
            list.Update();

            //currentWeb.Update();
        }

        public void CreateTweetsList()
        {

            //web.AllowUnsafeUpdates = true;
            Guid newListGuid = currentWeb.Lists.Add(Properties.Settings.Default.UserTweetsListName, "Tweets", SPListTemplateType.GenericList);

            SPList list = currentWeb.Lists[newListGuid];
            list.OnQuickLaunch = true;
            SPField field;

            field = list.Fields.CreateNewField(SPFieldType.Text.ToString(), "Tweet");
            field.Required = true;
            field.DefaultValue = "";
            list.Fields.Add(field);

            field = list.Fields.CreateNewField(SPFieldType.Boolean.ToString(), "PostedToFB");
            field.Required = false;
            field.DefaultValue = "false";
            field.Description = "Posted to FaceBook";
            list.Fields.Add(field);
 
            field = list.Fields.CreateNewField(SPFieldType.Boolean.ToString(), "PostedToTwitter");
            field.Required = false;
            field.DefaultValue = "false";
            field.Description = "Posted to Twitter";
            list.Fields.Add(field);

            field = list.Fields.CreateNewField(SPFieldType.Text.ToString(), "Author");
            field.Required = false;
            field.Description = "The primary author";
            list.Fields.Add(field);

            //Copy settings from the All Items view and then delete the view
            string query = list.Views["All Items"].Query;
            SPViewCollection viewcoll = list.Views;
            Guid viewID = list.Views["All Items"].ID;
            viewcoll.Delete(viewID);

            //SPViewFieldCollection viewfields = list.Views[viewID].ViewFields;
            //viewfields.DeleteAll();
            //viewfields.Add("Edit");
            //viewfields.Add("Follower");
            //viewfields.Add("IsAllowed");
            //list.Views["All Items"].Update();

            System.Collections.Specialized.StringCollection viewFields = new System.Collections.Specialized.StringCollection();

            viewFields.Add("Edit");
            viewFields.Add("Tweet");
            viewFields.Add("PostedToFB");
            viewFields.Add("PostedToTwitter");
            //viewFields.Add("Author");
            viewFields.Add(list.Fields["Created"].InternalName);

            // Add the view to the list
            list.Views.Add("All Items", viewFields, query, 100, true, true);

            list.Update();
            //currentWeb.Update();
        }

        private void UpdateLog(string Message, EventLogEntryType msgType)
        {
            try
            {
                System.Diagnostics.EventLog.WriteEntry("My Site Created Handler", Message, msgType);
            }
            catch
            {
                //ignore
            }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                EventLog eventlog = new EventLog();
                eventlog.Source = "MySiteFeatureStaple";
                eventlog.WriteEntry("Starting De-activation of the MySite Master Page Switcher Feature");

                try
                {
                    //SPSite mysite = properties.Feature.Parent as SPSite;
                    SPWeb myweb = (SPWeb)properties.Feature.Parent;
                    if (myweb.WebTemplate == "SPSPERS")
                    {
                        using (myweb)
                        {
                            if (myweb.MasterUrl.Contains("custom.master"))
                            {
                                myweb.MasterUrl = myweb.MasterUrl.Replace("custom.master", "default.master");

                                myweb.ApplyTheme("none");

                                currentWeb.Webs["Blog"].MasterUrl = currentWeb.MasterUrl.Replace("custom.master", "default.master");
                                currentWeb.Webs["Blog"].CustomMasterUrl = currentWeb.MasterUrl.Replace("custom.master", "default.master");
                            }
                            myweb.Update();
                            eventlog.WriteEntry("Removed custom master page from site using 'SPSPERS' template");
                        }
                    }

                    if (myweb.WebTemplate == "SPSMSITEHOST")
                    {
                        using (myweb)
                        {
                            if (myweb.MasterUrl.Contains("custom.master"))
                            {
                                myweb.MasterUrl = myweb.MasterUrl.Replace("custom.master", "default.master");
                                myweb.ApplyTheme("none");
                            }
                            myweb.Update();
                            eventlog.WriteEntry("Removed custom master page from site using 'SPSMSITEHOST' template");
                        }
                    }
                }
                catch (Exception e)
                {
                    eventlog.WriteEntry(String.Format("Error de-activating MySite master page switcher feature {0} : ", e.Message));
                }
            });


        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
            //throw new Exception("The method or operation is not implemented.");
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            //throw new Exception("The method or operation is not implemented.");
        }

        /// <summary>
        /// Enable the blogs on the current hosted my site 
        /// when the feature is activated
        /// </summary>
        public void DeployBlogs()
        {

            using (SPWeb blogWeb = currentWeb.Webs.Add("blog", "Blog", String.Empty, 1033, currentWeb.Site.GetWebTemplates(1033)["Blog#0"], false, false))
            {
                blogWeb.MasterUrl = currentWeb.MasterUrl;
                blogWeb.CustomMasterUrl = currentWeb.CustomMasterUrl;
                blogWeb.Update();

                // Enable the Moderation of the Posts
                SPList posts = blogWeb.Lists["Posts"];
                posts.EnableModeration = false;
                posts.Update();

                // Disable the Attachment Menu from Comments
                SPList comments = blogWeb.Lists["Comments"];
                comments.EnableAttachments = false;
                comments.WriteSecurity = 2;
                comments.Update();

                // change the default view of post list, remove the category and created by column
                SPView postView = posts.Views["All Posts"];

                postView.ViewFields.DeleteAll();
                // postView.ViewFields.Delete("PostCategory");
                //postView.ViewFields.Delete("Author");
                postView.ViewFields.Add("LinkTitleNoMenu");
                postView.ViewFields.Add("PublishedDate");
                postView.ViewFields.Add("NumComments");
                postView.ViewFields.Add("Edit");

                postView.Update();

            }
        }

        private int GetSiteNodeIndex(SPWeb web)
        {
            int i = 0;
            SPNavigationNodeCollection nodes = web.Navigation.QuickLaunch;
            foreach (SPNavigationNode n in nodes)
            {
                if (n.Id == 1026)
                {
                    return i;
                }
                i = i + 1;
            }
            return -1;
        }
    }
}
